package top.pro51.blog_admin.service;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.pro51.blog_admin.NotFoundException;
import top.pro51.blog_admin.dao.TypeRepository;
import top.pro51.blog_admin.po.Type;

import java.util.List;

@Service
public class TypeServiceImpl implements TypeService {

    @Autowired
    private TypeRepository typeRepository;

    /**
     * @Description 新增保存
     * @Author WangWenpeng
     * @Date 10:52 2020/7/28
     * @Param [type]
     */
    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    /**
     * @Description 用id查询一个
     * @Author WangWenpeng
     * @Date 10:52 2020/7/28
     * @Param [id]
     */
    @Transactional
    @Override
    public Type getType(Long id) {
        return typeRepository.getOne(id);
    }

    /**
     * @Description 用名称查询一个
     * @Author WangWenpeng
     * @Date 10:53 2020/7/28
     * @Param [name]
     */
    @Override
    public Type getTypeByName(String name) {
        return typeRepository.findByName(name);
    }

    /**
     * @Description 分类列表
     * @Author WangWenpeng
     * @Date 10:53 2020/7/28
     * @Param [pageable]
     */
    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    @Override
    public List<Type> listType() {
        return typeRepository.findAll();
    }


    @Override
    public List<Type> listTypeTop(Integer size) {
        Pageable pageable = PageRequest.of(0, size, Sort.by(Sort.Direction.DESC, "blogs.size"));
        return typeRepository.findTop(pageable);
    }


    /**
     * @Description 修改分类
     * @Author WangWenpeng
     * @Date 10:58 2020/7/28
     * @Param [id, type]
     */
    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
        Type t = typeRepository.getOne(id);
        if (t == null) {
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(type, t);
        return typeRepository.save(t);
    }

    /**
     * @Description 删除分类
     * @Author WangWenpeng
     * @Date 10:58 2020/7/28
     * @Param [id]
     */
    @Transactional
    @Override
    public void deleteType(Long id) {
        typeRepository.deleteById(id);
    }
}
